
const db = require('../db/index')
const crypto = require('crypto');
// 模拟的商户信息（虚拟的）
const appId = 'wx3036dc5d51baca90';
const mchId = '1538897491';
const apiKey = 'E9C64B67C6084772B1803E0872B9A909';  // 虚拟的 API 密钥

// 创建随机字符串
function generateNonceStr(length = 32) {
  const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
  let nonceStr = '';
  for (let i = 0; i < length; i++) {
    nonceStr += chars.charAt(Math.floor(Math.random() * chars.length));
  }
  return nonceStr;
}

// 生成虚拟支付签名
function generateSign(params) {
  const keys = Object.keys(params).sort();
  const queryString = keys.map(key => `${key}=${params[key]}`).join('&');
  const stringSignTemp = `${queryString}&key=${apiKey}`;
  return crypto.createHash('md5').update(stringSignTemp).digest('hex').toUpperCase();
}


exports.allCoupons = (req, res) => {
  const query = 'SELECT * FROM Coupons WHERE status = "active"';

  db.query(query, (err, results) => {
    if (err) {
      console.error('查询错误:', err);
      return res.status(500).json({ message: '查询失败' });
    }
    res.json({ success: true, message: '优惠券获取成功', data: results });  // 返回所有有效的优惠券
  });
};

exports.usedCoupons = (req, res) => {
  const { couponCode } = req.params;
  const query = 'UPDATE Coupons SET status = "used" WHERE coupon_code = ? AND status = "active"';

  db.query(query, [couponCode], (err, results) => {
    if (err) {
      console.error('更新错误:', err);
      return res.status(500).json({ message: '更新失败' });
    }
    if (results.affectedRows === 0) {
      return res.status(404).json({ message: '优惠券未找到或已被使用' });
    }
    res.json({ message: '优惠券已使用' });
  });
};

exports.form = (req, res) => {
  const { name, phone, openid } = req.body;

  // 判断请求参数是否有效
  if (!name || !phone) {
    return res.status(400).json({ error: 'Name and phone are required' });
  }

  // 使用 SQL 插入数据
  const query = 'UPDATE users SET full_name=?,phone_number=? WHERE openid=?';

  db.query(query, [name, phone, openid], (err, results) => {
    if (err) {
      console.error('Database error:', err);
      return res.status(500).json({ error: 'Failed to add user' });
    }

    // 返回成功响应
    res.status(201).json({ message: 'User added successfully' });
  });
}

exports.getuserinfo = (req, res) => {
  const openid = req.params.openid;
  const query = `select user_id,full_name, phone_number FROM users where openid=?`

  db.query(query, openid, (err, results) => {
    if (err) {
      console.error('查询错误:', err);
      return res.status(500).json({ message: '查询失败' });
    }
    res.json({ success: true, message: '用户信息获取成功', data: results });  // 返回所有有效的优惠券
  })

}

exports.createOrders = (req, res) => {
  const { user_id, room_id, check_in_date, check_out_date, total_price } = req.body;
  console.log(user_id, room_id, check_in_date, check_out_date, total_price)
  const query = `INSERT INTO orders (user_id, room_id, check_in_date, check_out_date, total_price)
VALUES (?,?,?,?,?);`
  db.query(query, [user_id, room_id, check_in_date, check_out_date, total_price], (err, results) => {
    if (err) {
      return res.status(500).json({ message: '数据插入失败', err });
    }
    res.json({ success: true, message: '新增一条订单记录', data: results });  // 返回订单字段
  })
}

exports.getorderId = (req, res) => {
  const { room_id, user_id } = req.params
  const query = `SELECT * FROM orders WHERE room_id=? AND user_id=? AND order_status='pending'`;

  console.log(room_id, user_id);

  db.query(query, [room_id, user_id], (err, results) => {
    if (err) {
      console.log(err);
      return res.status(500).json({ message: '订单表数据查询失败', err });
    }
    res.json({ success: true, message: '订单表数据查询成功', data: results });  // 返回订单字段
  })
}





// 模拟创建预支付订单


exports.payOrder = (req, res) => {
  const { openid, totalFee, body } = req.body;  // 从请求中获取用户的openid、金额和商品描述
  console.log(openid, totalFee, body);

  if (!openid || !totalFee || !body) {
    return res.status(400).json({ error: 'Missing required parameters' });
  }

  // 模拟生成预支付订单
  const nonceStr = generateNonceStr();
  const prepayId = `prepay_${nonceStr}`;  // 模拟的预支付订单号
  console.log(nonceStr, prepayId)
  // 构建虚拟的预支付订单响应
  const params = {
    appid: appId,
    mch_id: mchId,
    nonce_str: nonceStr,
    body: body,
    out_trade_no: prepayId,  // 商户订单号
    total_fee: totalFee,     // 支付金额（单位：分）
    spbill_create_ip: '127.0.0.1',  // 用户的IP地址（可以是测试IP）
    notify_url: 'http://hotel.ttt:3007/protected/payment/notify',  // 支付成功后的回调地址
    trade_type: 'JSAPI',  // 交易类型，JSAPI表示小程序支付
    openid: openid,  // 用户的openid
  };

  // 模拟签名
  const sign = generateSign(params);
  params.sign = sign;

  console.log(sign, params.sign)

  // 返回预支付订单信息
  res.json({
    success: true,
    prepay_id: prepayId,
    params: params,
  });
}



exports.payment = (req, res) => {
  const { status, order_id, amount, payment_method, transaction_id } = req.body;
  const query = `INSERT INTO payments (order_id,amount,payment_method,payment_status,transaction_id)VALUES (?,?,?,'successful',?);`
  const query1 = `INSERT INTO payments (order_id,amount,payment_method,payment_status,transaction_id)VALUES (?,?,?,'pending',?);`
  if (status) {
    console.log(`支付成功，订单号：${transaction_id}, 金额：${amount}`);
    db.query(query, [order_id, amount, payment_method, transaction_id], (err, results) => {
      if (err) {
        return res.status(500).json({ message: '数据插入失败', err });
      }
      res.json({ success: true, message: '新增一条订单记录', data: results });  // 返回订单字段
    })
  }
  if (!status) {
    console.log(`取消支付，订单号：${transaction_id}, 金额：${amount}`);
    db.query(query1, [order_id, amount, payment_method, transaction_id], (err, results) => {
      if (err) {
        return res.status(500).json({ message: '数据插入失败', err });
      }
      res.json({ success: true, message: '新增一条订单记录', data: results });  // 返回订单字段
    })
  }
}

exports.usedOrder = (req, res) => {
  const { payment_status, order_status, order_id } = req.body;
  console.log(payment_status, order_status, order_id)
  const query = 'UPDATE orders SET payment_status = ?, order_status=? WHERE order_id = ?';
  db.query(query, [payment_status, order_status, order_id], (err, results) => {
    if (err) {
      return res.status(500).json({ message: '更新失败' }, err);
    }
    if (results.affectedRows === 0) {
      return res.status(404).json({ message: '该订单未找到' });
    }
    res.json({ message: '修改订单状态成功', data: results });
  });
};

exports.orderMessage = (req, res) => {
  const order_id = req.params.order_id
  console.log(order_id);

  const query = `select * from orders where order_id=?`
  db.query(query, order_id, (err, results) => {
    if (err) {
      return res.status(500).json({ message: '订单表数据查询失败' })
    }
    res.json({ success: true, message: '订单数据查询成功', data: results });
  })
}

exports.paymentMessage = (req, res) => {
  const order_id = req.params.order_id
  console.log(order_id);

  const query = `select * from payments where order_id=?`
  db.query(query, order_id, (err, results) => {
    if (err) {
      return res.status(500).json({ message: '订单支付表数据查询失败' })
    }
    res.json({ success: true, message: '订单支付数据查询成功', data: results });
  })
}

exports.roomMessage = (req, res) => {
  const room_id = req.params.room_id
  const query = `select * from rooms where room_id=?`
  db.query(query, room_id, (err, results) => {
    if (err) {
      console.log(err);

      return res.status(500).json({ message: '房间信息查询失败' })
    }
    res.json({ success: true, message: '房间信息查询成功', data: results });
  })
}

exports.usedPayment = (req, res) => {
  const { payment_status, order_id } = req.params
  console.log('qqqq', payment_status, order_id);

  console.log('ccc', order_id);

  const sql = `UPDATE payments SET payment_status =? WHERE order_id = ?`;
  db.query(sql, [payment_status, order_id], (err, results) => {
    if (err) {
      console.log(err);
      return res.status(500).json({ message: '更改支付状态失败' })
    }
    res.json({ success: true, message: '更改支付状态成功', data: results });
  })
}

exports.updataInfo = (req, res) => {
  const { full_name, phone_number, user_id } = req.body
  console.log(full_name, phone_number, user_id);
  const sql = `UPDATE users SET full_name=?,phone_number=? WHERE user_id = ?`
  db.query(sql, [full_name, phone_number, user_id], (err, results) => {
    if (err) {
      console.log('个人信息修改失败', err);
      return res.status(500).json({ message: '个人信息修改失败' })
    }
    res.json({ success: true, message: '个人信息修改成功', data: results });
  })
}


exports.allorderMessage = (req, res) => {
  const { user_id, payment_status, order_status } = req.body
  console.log(user_id, payment_status, order_status);

  const sql = `select * from orders where user_id=? AND payment_status=? AND order_status=? `
  const sql1 = `select * from orders where user_id=?`

  if (payment_status == 0 && order_status == 0) {
    db.query(sql1, user_id, (err, results) => {
      if (err) {
        return res.status(500).json({ message: '订单表数据查询失败' })
      }
      res.json({ success: true, message: '全部订单数据查询成功', data: results });
    })
  }
  else {
    console.log('1111');

    db.query(sql, [user_id, payment_status, order_status], (err, results) => {
      if (err) {
        return res.status(500).json({ message: '订单表数据查询失败' })
      }
      res.json({ success: true, message: '订单数据查询成功', data: results });
    })
  }
}

exports.Instereviews = (req, res) => {
  const { user_id, room_id, room_name, order_id, rating, comment } = req.body
  console.log(user_id, room_id, room_name, order_id, rating, comment)
  const sql = `INSERT INTO reviews (user_id,room_id,room_name,order_id,rating,comment)VALUES (?,?,?,?,?,?);`
  db.query(sql, [user_id, room_id, room_name, order_id, rating, comment], (err, results) => {
    if (err) {
      console.log(err);
      
      return res.status(500).json({ message: '评价表新增失败' })
    }
    res.json({ success: true, message: '评价表新增成功', data: results });
  })
}





